from typing import List, Dict, Any, Optional
import logging

logger = logging.getLogger(__name__)

def merge_voice_settings(character_profile: Dict, base_settings: Optional[Dict] = None) -> Optional[Dict]:
    """
    合并角色配置中的语音设置
    
    Args:
        character_profile: 角色配置
        base_settings: 基础设置
        
    Returns:
        合并后的语音设置
    """
    if not character_profile or "voice_settings" not in character_profile:
        return base_settings
        
    voice_settings = character_profile["voice_settings"]
    
    # 新数据结构：voice_settings直接包含所有设置
    # 检查是否为新格式（包含vol, pitch, speed等字段）
    if isinstance(voice_settings, dict) and any(key in voice_settings for key in ["vol", "pitch", "speed", "voice_id"]):
        # 新格式：直接返回voice_settings
        logger.info(f"使用新数据结构的语音设置: {voice_settings}")
        return voice_settings
    
    # 兼容旧格式：检查是否有minmax格式
    if isinstance(voice_settings, dict) and "minmax" in voice_settings:
        voice_settings = voice_settings["minmax"]
        # 合并顶层配置到语音设置
        for key in ["language_boost", "timber_weights"]:
            if key in character_profile and key not in voice_settings:
                voice_settings[key] = character_profile[key]
    
    return voice_settings


def format_messages_for_api(messages: List[Any]) -> List[Dict[str, str]]:
    """
    将消息对象列表转换为API格式的字典列表
    
    Args:
        messages: 消息对象列表
        
    Returns:
        字典格式的消息列表
    """
    return [{"role": msg.role, "content": msg.content} for msg in messages]


def build_tts_params(text: str, emotion: str = "neutral", voice_settings: Optional[Dict] = None) -> Dict[str, Any]:
    """
    构建TTS参数
    
    Args:
        text: 要转换的文本
        emotion: 情绪
        voice_settings: 语音设置
        
    Returns:
        TTS参数字典
    """
    # 默认参数
    tts_params = {
        "text": text,
        "model": "speech-02-turbo",
        "voice_id": "female-tianmei",
        "speed": 1.0,
        "vol": 1.0,
        "pitch": 0,
        "stream": False,
        "language_boost": "auto",
        "emotion": emotion
    }
    
    # 应用自定义设置
    if voice_settings:
        for key in ["voice_id", "speed", "vol", "pitch", "language_boost", "timber_weights"]:
            if key in voice_settings:
                tts_params[key] = voice_settings[key]
        
        # 覆盖情绪设置（如果指定）
        if voice_settings.get("emotion"):
            tts_params["emotion"] = voice_settings["emotion"]
    
    return tts_params


def create_sse_event(event_type: str, data: Dict[str, Any]) -> str:
    """
    创建SSE事件字符串
    
    Args:
        event_type: 事件类型
        data: 事件数据
        
    Returns:
        SSE格式的事件字符串
    """
    import json
    return f"event: {event_type}\ndata: {json.dumps(data)}\n\n"


def is_context_query(message: str, keywords: List[str]) -> bool:
    """
    检查是否为上下文查询
    
    Args:
        message: 用户消息
        keywords: 关键词列表
        
    Returns:
        是否为上下文查询
    """
    return any(keyword in message for keyword in keywords)


def extract_user_messages(history: List[Dict]) -> List[str]:
    """
    从历史记录中提取用户消息
    
    Args:
        history: 历史记录
        
    Returns:
        用户消息列表
    """
    return [msg["content"] for msg in history if msg["role"] == "user"]


def should_include_emotion(generate_voice: bool, request_emotion: bool) -> bool:
    """
    判断是否应该包含情感分析
    
    Args:
        generate_voice: 是否生成语音
        request_emotion: 请求中是否要求情感分析
        
    Returns:
        是否应该包含情感分析
    """
    return generate_voice or request_emotion 